import axios from "axios";
import { ElLoading } from "element-plus";

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  // timeout: 5000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

let loadingInstance = null; // Loading实例
let requestCount = 0; // 请求计数器

// 创建Loading实例
function createLoading() {
  loadingInstance = ElLoading.service({
    fullscreen: true,
    lock: true,
    text: "加载中...",
    background: "rgba(0, 0, 0, 0.7)",
  });
}

// 关闭Loading实例
function closeLoading() {
  if (loadingInstance) {
    loadingInstance.close();
    loadingInstance = null;
  }
}

// 创建一个Map对象用于存储正在请求中的接口
const pendingRequests = new Map();
// 生成请求标识
function generateRequestKey(config) {
  return `${config.method}-${config.url}-${JSON.stringify(config.params)}-${JSON.stringify(config.data)}`;
}

// 取消重复请求
function cancelPendingRequest(config, cancelDuplicate) {
  const requestKey = generateRequestKey(config);
  if (cancelDuplicate && pendingRequests.has(requestKey)) {
    const cancelToken = pendingRequests.get(requestKey);
    cancelToken.cancel("Duplicate request canceled");
    pendingRequests.delete(requestKey);
  }
}

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const accessToken = localStorage.getItem("token");
    if (accessToken) {
      config.headers.Authorization = accessToken;
    }
    // 取消重复请求
    cancelPendingRequest(config, config.cancelDuplicate);
    // 创建CancelToken对象并保存到pendingRequests中
    if (config.cancelDuplicate !== false) {
      // 检查是否明确将cancelDuplicate设置为false
      config.cancelToken = new axios.CancelToken((cancelToken) => {
        const requestKey = generateRequestKey(config);
        pendingRequests.set(requestKey, cancelToken);
      });
    }
    // 请求计数器加一，并创建Loading实例
    requestCount++;
    if (requestCount === 1 && config.headers.showLoading !== false) {
      createLoading();
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { code, msg } = response.data;
    if (code === "200") {
      const requestKey = generateRequestKey(response.config);
      pendingRequests.delete(requestKey);
      // 请求计数器减一，并关闭Loading实例
      requestCount--;
      if (requestCount === 0) {
        closeLoading();
      }
      return response.data;
    }
    // 刷新token
    if (code === 401) {
      console.log("刷新token");
    }
    // 处理响应错误
    return Promise.reject(new Error(msg || "Error"));
  },
  (error) => {
    // 请求计数器减一，并关闭Loading实例
    requestCount--;
    if (requestCount === 0) {
      closeLoading();
    }
    return Promise.reject(error.message);
  }
);

export default service;
